import { useEffect, useRef, useState } from "react"
import { getWindowInfo } from "@/utils/core"
import { getLaunchOptionsSync, usePageScroll, useRouter } from "@tarojs/taro"
import { throttle } from "./common"
import { navigationPlugin } from "./router"

export { useSetState } from "@vinsurs/react-hooks"

/** 导航栏布局基本信息
 * @default
 */
export const NAVIGATION_BASE_LAYOUT: NavigationBaseLayout = {
  statusBarHeight: 20,
  navigationHeight: 60
}
/** 自定义导航栏布局信息
 *  @default
 */
export const NAVIGATION_LAYOUT: NavigationLayout = {
  ...NAVIGATION_BASE_LAYOUT,
  menuButtonHeight: 50,
  menuButtonPadding: 5,
  navigationOffset: 0
}
/**
 * 获取设备状态栏和导航栏的布局信息, 用于自定义导航栏
 * @param [navigationOffset=0] 计算导航栏高度的上下偏移量, 取值越大导航栏高度越高，最小值为`-menuButtonPadding`, 默认为0
 */
export function useLayout(navigationOffset = 0): [NavigationLayout, NavigationLayoutIsReady] {
  const [layout, setLayout] = useState<NavigationLayout>(NAVIGATION_LAYOUT)
  const [isReady, setIsReady] = useState<NavigationLayoutIsReady>(false)
  useEffect(() => {
    const { statusBarHeight, menuButtonRect } = getWindowInfo()
    const menuButtonPadding = menuButtonRect.top - statusBarHeight
    setLayout({
      statusBarHeight,
      menuButtonHeight: menuButtonRect.height,
      menuButtonPadding,
      navigationHeight:
        menuButtonRect.height +
        Math.min(menuButtonPadding, menuButtonPadding + navigationOffset) * 2,
      navigationOffset
    })
    setIsReady(true)
  }, [])
  return [layout, isReady]
}
/**
 * 页面自定义导航栏 导航栏背景色透明度
 * @param [skyline=false] ~~当前页面是否开启skyline模式, 由于开启skyline模式后，页面禁止滚动，usePageScroll此时失效，需要传给外部一个处理scrollTop的方法~~不再需要判断是否是skyline
 */
export function useNavigationOpacity(_ = false): [number, (scrollTop: number) => void] {
  const [opacity, setOpacity] = useState(0)
  const updateOpacity = useRef(
    throttle((scrollTop: number) => {
      const needle = 120
      const _opacity = Math.min(scrollTop, needle) / needle
      setOpacity(_opacity)
    }, 30)
  )
  const scrollHandler = updateOpacity.current
  usePageScroll(({ scrollTop }) => {
    updateOpacity.current(scrollTop)
  })
  // @ts-ignore
  return [opacity, scrollHandler]
}

/** 用于处理小程序跳转小程序 */
export function useRefererMini() {
  const router = useRouter()
  useEffect(() => {
    const launchOptions = getLaunchOptionsSync()
    if (launchOptions.scene === 1037 && router.params) {
      const { pn } = router.params
      if (pn) {
        const [_, pluginName, pageName] = pn.split(":")
        if (pluginName && pageName) {
          console.log("[useRefererMini] pluginName: %s, pageName: %s", pluginName, pageName)
          navigationPlugin(pageName, null)
        }
      }
    }
  }, [])
}
